package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.Session;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //验证码发送
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
//        输入手机号 -> 点击获取验证码 -> 发送ajax请求后台
        String phone = user.getPhone();
//        1、后台获取手机号【13399998888】
        String code = RandomUtil.randomNumbers(6);
//        2、随机生成六位数字验证码【123456】
        //session.setAttribute(phone,code);
        redisTemplate.opsForValue().set("code:"+phone,code,5, TimeUnit.MINUTES);
//        3、调用SMSUtils,给该手机号发送相应的验证码短信
        System.out.println(code);
//        4、将该验证码存入到session中，使用手机号作为key，值就是验证码 存入Redis中

//-> 此时用户的手机应该收到了验证码短信：
        return R.success("验证码发送成功");
    }

    //核对验证码
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,String> map,HttpSession session){
        String phone = map.get("phone");
        String code = map.get("code");
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            return R.error("手机号或者验证码不能为空");
        }

        //String codeInSession = (String) session.getAttribute(phone);
        String codeInSession = (String)redisTemplate.opsForValue().get("code:"+phone);
        redisTemplate.delete("code:"+phone);

        if(code.equals(codeInSession)){
            User user = new User();
            user.setPhone(phone);
            session.setAttribute("user",user);

            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User one = userService.getOne(lqw);
            if(one==null){
                userService.save(user);
            }
            session.setAttribute("user",one);
            return R.success("登录成功");
        }

        return R.error("登录失败");
    }

    //登出
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
